<?php
/*
 *      npc.class.php
 *      
 *      Copyright 2009 Valery Tverdohleb <tvsdesign@gmail.com>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

class NPC
{
	protected $npcList = array();
	
	public function __construct($coords)
	{
		$this->load($coords);
	}
	
	public function load($coords)
	{
		$this->npcList = array();
		$stmt = Engine::get()->db->prepare('SELECT `id`, `name`, `dialog` FROM `npcs` WHERE `X` = :X AND `Y` = :Y AND `Z` = :Z AND `L` = :L;');
		$stmt->bindValue(':X',$coords['X']);
		$stmt->bindValue(':Y',$coords['Y']);
		$stmt->bindValue(':Z',$coords['Z']);
		$stmt->bindValue(':L',$coords['L']);
		$stmt->execute();
		$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
		foreach ($rows as $v)
		{
			$this->npcList[$v['id']] = array('name' => $v['name'], 'dialog'=>unserialize($v['dialog']));
		}
	}
	
	public function listNPCs()
	{
		$r = array();
		foreach ($this->npcList as $k => $v)
		{
			$r[] = array('id'=>$k, 'name'=>$v['name']);
		}
		return $r;
	}
	
	public function get($id)
	{
		if (array_key_exists($id, $this->npcList))
		{
			return $this->npcList[$id];
		}
		else
		{
			return null;
		}
	}
	
	public function isHere($id)
	{
		return array_key_exists($id, $this->npcList);
	}
	
	public function dialog($npcid, $pid = null)
	{
		if (!$this->isHere($npcid)) return null;
		if ($pid != null)
		{
			$npc = $this->get($npcid);
			return $npc['dialog'][$pid];
		}
		else
		{
			$npc = $this->get($npcid);
			return $npc['dialog'];
		}
	}
	
	public function name($npcid)
	{
		$npc = $this->get($npcid);
		return $npc['name'];
	}
	
}

?>
